package com.kwin.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class CookieApp22 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String id = req.getParameter("id");
        Book book = DB.getAll().get(id);
        resp.getWriter().write("书的编号是：" + book.getId() + "<br/>");
        resp.getWriter().write("书的名称是：" + book.getName() + "<br/>");
        resp.getWriter().write("书的作者是：" + book.getAuthor() + "<br/>");

        String bookHistory = makeHistory(req, id);
        Cookie cookie = new Cookie("bookHistory", bookHistory);
        cookie.setMaxAge(3000);
        resp.addCookie(cookie);
    }

    private String makeHistory(HttpServletRequest req, String id) {
        String bookHistory = null;
        Cookie[] cookies = req.getCookies();
        for (int i = 0;cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("bookHistory")) {
                bookHistory = cookies[i].getValue();
            }
        }
        System.out.println(bookHistory);

        if (bookHistory == null) {
            return id;
        } else {
            String[] strings = bookHistory.split("\\_");
            List<String> list = Arrays.asList(strings);
            LinkedList<String> linkedList = new LinkedList<>();
            linkedList.addAll(list);

            if (linkedList.contains(id)) {
                linkedList.remove(id);
                linkedList.addFirst(id);
            } else {
                if (linkedList.size() >= 3) {
                    linkedList.removeLast();
                    linkedList.addFirst(id);
                }else {
                    linkedList.addFirst(id);
                }
            }

            StringBuffer stringBuffer = new StringBuffer();
            for (String s : linkedList) {
                stringBuffer.append(s + "_");
            }

            return stringBuffer.deleteCharAt(stringBuffer.length() - 1).toString();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
